// pages/goods/index.js
const app = getApp()
import http from '../../utils/request.js';
import alert from '../../utils/alert.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tableId:0,
    tableInfo:{},
    orderNo: '',
    personNum: 0,
    menus: [],
    scrollHeight: "500px",
    toNavView: '',
    toGoodsView: '',
    navActive: '',
    vertical: true,
    circular: true,
    indexSize: 0,
    //sku选择框是否显示
    skuPopupvisible: false,
    //sku框的标题
    skuPopupTitle: '请选择规格',
    skuSelect: [],
    skuGoodsAllList:[],
    skuList: [],
    skuKey: '',
    skuGoods: {},
    toGoodsList: [],
    totalGoodsPrice:0,
    totalSkuPrice:0,
    cartPopupVisible: false,
    toSkuGoodsArr: [],
    skuGoodsNums: [],
    goodsNums:[],
    skuCartGoods:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if (typeof (options.table_id) === 'undefined') {
      var table_id = 0;
    } else {
      var table_id = options.table_id;
      this.getTableName(table_id);
    }

    if (typeof (options.order_no) === 'undefined') {
      var order_no = '';
    } else {
      var order_no = options.order_no;
    }
    var res = wx.getSystemInfoSync();
    this.setData({
      urlInfo: 'add',
      tableId: table_id,
      orderNo: order_no,
      openid: wx.getStorageSync('userInfo').openid,
      scrollHeight: res.windowHeight - 46 + 'px'
    });

    this.getGoodsMenus();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getGoodsMenus: function () {
    var that = this;
    var goods=[];
    var goodsNums=that.data.goodsNums;

    http.post(app.config.service.getGoodsList).then(data => {
      var navActive = data[0].cate.id;
      that.setData({
        menus:data,
        navActive: navActive
      })
    }, err => {
      alert.alert(err)
    });
  },

  navClick(e) {
    var navActive = e.currentTarget.id;
    this.setData({
      navActive: navActive,
      toNavView: 'cate_'+navActive,
      indexSize: e.currentTarget.dataset.index
    })
  },

  swiperChange(e) {
    var goods = this.data.menus;
    var navActive = goods[e.detail.current].cate.id;
    this.setData({
      navActive: navActive,
      toNavView: 'cate_'+navActive,
      indexSize: e.detail.current
    })
  },

  onInputNumberChange: function (e) {
    console.log(e)
    var goods = e.currentTarget.dataset.goods;
    var menus = this.data.menus;
    var goodsNums = this.data.goodsNums;
    var totalGoodsPrice = 0;
    menus.forEach(function (cate) {
      cate.goods.forEach(function (value) {
        if (value.key == goods.key) {
            var oldvalue=goodsNums[value.key]
            console.log(oldvalue);
          console.log(e.detail.value)
          if (typeof (oldvalue) === 'undefined' || oldvalue < e.detail.value){
            if (e.detail.value < goods.min_sale_num) {
              value.goods_num = goods.min_sale_num
            } else {
              value.goods_num = e.detail.value
            }
          }else{
            if (e.detail.value < goods.min_sale_num) {
              value.goods_num = 0
            } else {
              value.goods_num = e.detail.value
            }
          }
          console.log(value.goods_num)
          goodsNums[value.key] = value.goods_num
        }
        if (typeof (value.goods_num) !== "undefined") {
          totalGoodsPrice += (Math.round(value.goods_num * value.price * 100) / 100)
        }
      })
    })
    this.setData({ menus: menus, totalGoodsPrice: totalGoodsPrice, goodsNums: goodsNums })
    return;
  },

  onSkuInputNumberChange:function(e){
    var goods = e.currentTarget.dataset.goods;
    var totalSkuPrice = 0;
    var toSkuGoodsArr = this.data.toSkuGoodsArr;
    var skuGoodsNums = this.data.skuGoodsNums;
    var skuCartGoods=[];
    goods.goods_num = e.detail.value;
    toSkuGoodsArr[goods.key] = goods;
    skuGoodsNums[goods.key] = e.detail.value
    for (var skuGoods in toSkuGoodsArr){
      toSkuGoodsArr[skuGoods].unit="份"
      toSkuGoodsArr[skuGoods].meal_id=0
      skuCartGoods.push(toSkuGoodsArr[skuGoods])
      totalSkuPrice += (Math.round(toSkuGoodsArr[skuGoods].goods_num * toSkuGoodsArr[skuGoods].price * 100) / 100)
    }
    this.setData({ 
      toSkuGoodsArr: toSkuGoodsArr, 
      skuCartGoods: skuCartGoods, 
      totalSkuPrice: totalSkuPrice, 
      skuGoodsNums: skuGoodsNums, 
      skuGoods: goods
      })
  },

  selectSku: function (e) {
    var gid = e.currentTarget.dataset.id
    var skuGoodsNums = this.data.skuGoodsNums;
    var that = this;
    http.post(app.config.service.getGoodsSku, {goods_id: gid }).then(data => {
      var skuGoods = data.skuGoods;
      var toGoodsList = that.data.toGoodsList;

      if (typeof (skuGoodsNums[skuGoods.key]) != 'undefined') {
        skuGoods.goods_num = parseInt(skuGoodsNums[skuGoods.key]);
      } else {
        skuGoods.goods_num = 0
        skuGoodsNums[skuGoods.key]=0
      }
      
      that.setData({
        skuSelect: data.sku,
        skuList: data.list,
        skuKey: data.skuKey,
        skuGoods: skuGoods,
        skuGoodsNums: skuGoodsNums,
        skuPopupTitle: skuGoods.goods_name,
        skuPopupvisible: true
      })
    }, err => {
      alert.alert(err)
    });
  },

  onSkuGroupChange(e) {
    var field = e.currentTarget.dataset.group;
    var skuSelect = this.data.skuSelect;
    var skuList = this.data.skuList;
    var skuGoodsNums = this.data.skuGoodsNums;
    var skuKeyArr = [];
    var skuKey = '';
    var skuGoods = [];
    skuSelect[e.currentTarget.dataset.group].checkValue = parseInt(e.detail.value);
    //筛选出可用的key
    skuSelect.forEach(function (value, index) {
      skuKeyArr.push(value.checkValue);
    })
    //组合skuKey值
    skuKey = skuKeyArr.join('-');
    //取出元数据
    skuGoods = skuList[skuKey];
    //更新sku单选框中的数字
    skuGoods.goods_num = skuGoodsNums[skuGoods.key];
    //goodsNums[skuGoods.key]=0;
    this.setData({
      skuSelect: skuSelect,
      skuKey: skuKey,
      skuGoods: skuGoods
    })
  },

  onSkuClose() {
    this.setData({
      skuPopupvisible: false
    })
  },

  showCart: function () {
    this.setData({
      cartPopupVisible: true
    })
  },

  onCartClose: function () {
    this.setData({
      cartPopupVisible: false
    })
  },

  onClearCart: function () {
    this.setData({
      toGoodsList: [],
      toGoodsArr: [],
      goodsNums: [],
      cartPopupVisible: false,
      totalPrice: 0
    })
    wx.setStorage({
      key: 'toGoodsList',
      data: [],
    })
    wx.setStorage({
      key: 'toGoodsArr',
      data: [],
    })
    wx.setStorage({
      key: 'goodsNums',
      data: [],
    })
  },

  storageGoods: function (e) {
    var menus = this.data.menus;
    var toGoodsList = [];
    menus.forEach(function (cate) {
      cate.goods.forEach(function (value) {
        if(value.goods_num>0){
          if(typeof(value.sku_id)=='undefined'){
            value.sku_id=0;
          }
          if (typeof (value.goods_id) == 'undefined') {
            value.goods_id = 0;
          }
          if (typeof (value.meal_id) == 'undefined') {
            value.meal_id = 0;
          }
          if (typeof (value.is_start_dinner) == 'undefined') {
            value.is_start_dinner = 0;
          }
          if (typeof (value.pinzhu) == 'undefined') {
            value.pinzhu = '';
          }
          toGoodsList.push(value);
        }
      })
    })
    var goodsList = toGoodsList.concat(this.data.skuCartGoods);
    wx.setStorage({
      key: 'storageOrder',
      data: {
        table: this.data.tableInfo,
        order_no: this.data.orderNo,
        goods_list: goodsList,
        totalPrice:this.data.totalGoodsPrice+this.data.totalSkuPrice
      }
    })
    wx.navigateTo({
      url: './edit/index',
    })
  },

  getTableName: function (table_id){
    http.get(app.config.service.getTableInfo, {app_id:app.globalData.app_id,table_id:table_id}).then(data => {
      wx.setNavigationBarTitle({title:data.name+'：下单菜单'});
      this.setData({
        tableInfo:data
      });
    }, err => {
      alert.alert(err).then(res=>{
        wx.navigateBack({
          delta: 1,
        })
      },err=>{
        console.log(err)
      })
    });
  },
  showGoodsInfo:function(e){
    console.log(e)
    var goodsInfo = e.currentTarget.dataset.info;
    console.log(goodsInfo);
    if (goodsInfo.meal_id==0){
      var album = goodsInfo.album;
      album.push(goodsInfo.cover);
      wx.previewImage({
        current: album[0], // 当前显示图片的http链接
        urls: album // 需要预览的图片http链接列表
      })
    }else{
      wx.navigateTo({
        url: './info/index?meal_id='+ goodsInfo.meal_id,
      })
    }
  }
})